<template>
  <el-dialog
    :visible.sync="value"
    :title="title"
    width="500px"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <slot name="form-content"></slot>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit"
        >提交</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "ModalForm",
  props: {
    value: {
      type: Boolean,
      required: true,
    },
    title: {
      type: String,
      default: "表单提交",
    },
    form: {
      type: Object,
      required: true,
    },
    rules: {
      type: Object,
      default: () => ({}),
    },
    submitFunction: {
      type: Function,
      required: true,
    },
    closeDelay: {
      type: Number,
      default: 1000,
    },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;

        this.loading = true;
        try {
          await this.submitFunction(this.form);
          this.$message.success("提交成功！");
          setTimeout(() => {
            this.handleClose();
          }, this.closeDelay);
        } catch (error) {
          this.$message.error(error.message || "提交失败！");
        } finally {
          this.loading = false;
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
